<?php

namespace Hilaoyu\LaravelExtend\Services\Auth\Controllers;

use Hilaoyu\LaravelExtend\ControllerBase;

use Hilaoyu\LaravelExtend\Services\Auth\AuthService;
use Hilaoyu\LaravelExtend\Services\Captcha\CaptchaService;
use Hilaoyu\Utils\UtilSupport;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;


class AuthUsersProfileController extends ControllerBase
{

    public function changeMobile(Request $request){
        $user = AuthService::AuthenticatedUserFresh();
        if(!$user){
            return comResponse()->failed('未登录或登录已过期')->json();
        }
        $guard_key = AuthService::GuardKey();
        $user_id = data_get($user,'id','');

        $mobile = $request->input('mobile','');


        if (config('laravel-extend.services.captcha.registered', false)) {
            $code_id = $request->input('code_id', '');
            $code_val = $request->input('code_val', '');
            $captchaService = new CaptchaService();
            if (!$captchaService->verify($code_id, $code_val,$mobile)) {
                comResponse()->failed('验证码错误')->withErrors('验证码错误','code_val');
                return $this->renderingResponse();
            }
        }


        $data = ['mobile'=>$mobile];
        $check_exists = true;
        //如果作为客户端使用，先在用户中心修改
        if($client = AuthService::ProviderUseAsClient()){
            if(! $client->userUpdate(['id'=>$user_id],$data)){
                comResponse()->failed($client->getResult('message'))->withErrors($client->getError());
                return $this->renderingResponse();
            }
            $check_exists = false;
        }


        if(AuthService::SaveUser($data,$user_id,$guard_key,$check_exists)){
            comResponse()->success('修改成功');
        }else{
            comResponse()->failed('修改失败')->withErrors(AuthService::GetStaticError());
        }
        return $this->renderingResponse();
    }

    public function changeEmail(Request $request){
        $user = AuthService::AuthenticatedUserFresh();
        if(!$user){
            return comResponse()->failed('未登录或登录已过期')->json();
        }
        $guard_key = AuthService::GuardKey();
        $user_id = data_get($user,'id','');

        $email = $request->input('email','');

        if (config('laravel-extend.services.captcha.registered', false)) {
            $code_id = $request->input('code_id', '');
            $code_val = $request->input('code_val', '');
            $captchaService = new CaptchaService();
            if (!$captchaService->verify($code_id, $code_val,$email)) {
                comResponse()->failed('验证码错误')->withErrors('验证码错误','code_val');
                return $this->renderingResponse();
            }
        }

        $data = ['email'=>$email];
        $check_exists = true;
        //如果作为客户端使用，先在用户中心修改
        if($client = AuthService::ProviderUseAsClient()){
            if(! $client->userUpdate(['id'=>$user_id],$data)){
                comResponse()->failed($client->getResult('message'))->withErrors($client->getError());
                return $this->renderingResponse();
            }
            $check_exists = false;
        }


        if(AuthService::SaveUser($data,$user_id,$guard_key,$check_exists)){
            comResponse()->success('修改成功');
        }else{
            comResponse()->failed('修改失败')->withErrors(AuthService::GetStaticError());
        }
        return $this->renderingResponse();
    }

    public function changePassword(Request $request){


        $user = AuthService::AuthenticatedUserFresh();
        if(!$user){
            return comResponse()->failed('未登录或登录已过期')->json();
        }
        $guard_key = AuthService::GuardKey();

        $user_id = data_get($user,'id','');

        $old_password = $request->input('old_password','');
        $password = $request->input('password','');
        $password_confirm = $request->input('password_confirm','');

        if(empty($old_password)){
            return comResponse()->failed('原密码不能为空')->withErrors('原密码不能为空','old_password')->json();
        }
        if(empty($password)){
            return comResponse()->failed('新密码不能为空')->withErrors('新密码不能为空','password')->json();
        }

        if($password !== $password_confirm){
            return comResponse()->failed('两次输入的密码不一致')->withErrors('两次输入的密码不一致','password')->json();
        }

        if(true !== ($check = AuthService::CheckPasswordHandle($password,$user))){
            return comResponse()->failed((string)$check)->withErrors($check,'password')->json();
        }

        //如果作为客户端使用，先在用户中心修改
        if($client = AuthService::ProviderUseAsClient()){
            if(! $data = $client->changePassword($user_id,$old_password,$password)){
                comResponse()->failed($client->getResult('message'))->withErrors($client->getError());
                return $this->renderingResponse();
            }
            $hash_pass = data_get($data,'password','');
        }else{
            if(!$user->checkPassword($old_password)){
                comResponse()->failed('原密码错误')->withErrors('原密码错误','old_password');
                return $this->renderingResponse();
            }

            $hash_pass = AuthService::PasswordEn($password,$guard_key);
        }





        if(AuthService::SaveUser(['password'=>$hash_pass],$user_id,$guard_key,false)){
            UtilSupport::tryQuiet(function (){
                Auth::logout();
            });
            comResponse()->success('修改成功');
        }else{
            comResponse()->failed('修改失败')->withErrors(AuthService::GetStaticError());
        }
        return $this->renderingResponse();
    }

    protected function profileSave(Request $request){
        $id = AuthService::AuthenticatedUser('id');
        if(!$id){
            return comResponse()->failed('未登录或登录已过期')->withErrors($entity->getError());
        }

        $data = [
            //'account' => $request->input('account',''),
            'name' => $request->input('name',''),
            'sex' => $request->input('sex',''),
            'picture' => $request->input('picture',''),
            'summary' => $request->input('summary',''),
        ];


        if($user = AuthService::SaveUser($data,$id,'',false)){
            comResponse()->success('修改成功')->with($user->only([
                'name',
                'sex',
                'picture',
                'summary',
            ]));
        }else{
            comResponse()->failed('修改失败')->withErrors($entity->getError());
        }
        return $request->ajax() ? comResponse()->json() : comResponse()->back();
    }
}
